/*

 */
import { loginApi,userinfoApi } from '@/request/api.js';
import router from '@/router/index';
import { RouterData } from '@/utils/businessData.js';
import { constantRoutes } from '@/router';
// import store from '..';
const state = {
  token: '',
  roleId: 0,
  userinfo: {},
  loginInfo: {}
};

const mutations = {
  SET_TOKEN: (s, token) => {
    state.token = token;
  },
  SET_ROLEID: (s, roleId) => {
    state.roleId = roleId;
  },
  SET_USERINFO: (s, userinfo) => {
    state.userinfo = userinfo;
  },
  SET_LOGININFO: (s, loginInfo) => {
    state.loginInfo = loginInfo;
  }
};

const actions = {
  Login({ commit }, loginInfo) {
    console.log('获取登录信息', loginInfo);
    return new Promise((resolve,reject) => {
      loginApi(loginInfo).then((res) =>{
        commit('SET_TOKEN', res.token);
        sessionStorage.setItem('userToken', res.token);
        resolve(res);
      }).catch((err) => {
        console.error(err);
        reject(err);
      });
    });
  },

  getUserInfo({commit}, token) {
    return new Promise((resolve, reject) => {
      userinfoApi().then((res) => {
        commit('SET_ROLEID', res.roleId);
        commit('SET_USERINFO', res);

        let arr = [...res.power];
        let resultArr = RouterData(arr);
        // .push({ path: '*', redirect: '/', hidden: true })
        let combination = constantRoutes.concat(resultArr);
        router.addRoutes(combination);
        // console.log('组合后的路由', resultArr);
        localStorage.setItem('routerRefresh', JSON.stringify(resultArr));
        sessionStorage.setItem('routerAuth', JSON.stringify(resultArr));

        resolve(res);
      }).catch((error) => {
        reject(error);
      });
    });
  },

  logout({commit}) {
    commit('SET_ROLEID', '');
    commit('SET_USERINFO', '');
    commit('SET_TOKEN', '');
    localStorage.removeItem('routerRefresh');
    sessionStorage.removeItem('routerAuth');
    sessionStorage.removeItem('userToken');
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
